package com.demo.provider.controller.nsf;

import com.demo.provider.controller.DemoProviderInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequest;


@RestController
@RequestMapping("nsf")
public class NsfDemoController {

    @Autowired
    private HttpServletRequest request;


    /**
     * 熔断测试
     */
    int count = 0;

    private static final Logger log = LoggerFactory.getLogger(DemoProviderInfo.class);

//    @PostMapping("fault")
//    public String fault(String action){
////        if("branch_cancel".equals(action)){
////            throw new RuntimeException("demo-provider 返回500 报错");
////        }
//        throw new RuntimeException("demo-provider 返回500 报错");
////        return  "响应服务地址:" + request.getServerName()+":"+request.getServerPort();
//    }


    @GetMapping("fault")
    public String fault(String action){

        log.info("/nsf/fault demo-provider返回500报错");
        return new RuntimeException("provider 返回500报错") + request.getServerName() + ":" + request.getServerPort();
//        throw new RuntimeException("demo-provider 返回500 报错");

    }

    @GetMapping("timelay")
    public String timelay() throws InterruptedException {
        Thread.sleep(3000);
        log.info("/nsf/timelay this api timelay 3000ms!");
        System.out.println("demo-provider/nsf timelay is getd");
        return "timelay 3000ms";
    }

    @GetMapping("/content")
    public String content(String content) {
        String host = request.getServerName()+":"+request.getServerPort();
        if ("error".equals(content)) {
            log.error("/nsf/content {}", content);
            throw new RuntimeException(content);
        }
        if ("rand".equals(content)) {
            if (count++ % 3 == 0) {
                log.error("/nsf/content {}", content);
                throw new RuntimeException(content);
            }
        }
        log.info("/nsf/content {} from {} {}", content, host, System.lineSeparator());
        return content + " from "  + "[" + host  + "]" + System.lineSeparator();
    }

}
